<template>
  <div class="admin-review-manage">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <div class="search-container">
        <div class="search-row">
          <div class="search-item">
            <label>评分：</label>
            <div class="filter-buttons">
              <el-button 
                :type="searchParams.rating === null ? 'primary' : ''" 
                size="small"
                @click="searchParams.rating = null">
                全部
              </el-button>
              <el-button 
                :type="searchParams.rating === 5 ? 'primary' : ''" 
                size="small"
                @click="searchParams.rating = 5">
                ⭐⭐⭐⭐⭐ 5星
              </el-button>
              <el-button 
                :type="searchParams.rating === 4 ? 'primary' : ''" 
                size="small"
                @click="searchParams.rating = 4">
                ⭐⭐⭐⭐ 4星
              </el-button>
              <el-button 
                :type="searchParams.rating === 3 ? 'primary' : ''" 
                size="small"
                @click="searchParams.rating = 3">
                ⭐⭐⭐ 3星
              </el-button>
              <el-button 
                :type="searchParams.rating === 2 ? 'primary' : ''" 
                size="small"
                @click="searchParams.rating = 2">
                ⭐⭐ 2星
              </el-button>
              <el-button 
                :type="searchParams.rating === 1 ? 'primary' : ''" 
                size="small"
                @click="searchParams.rating = 1">
                ⭐ 1星
              </el-button>
            </div>
          </div>
          
          <div class="search-item">
            <label>评价内容：</label>
            <el-input 
              v-model="searchParams.content" 
              placeholder="请输入评价内容关键词" 
              clearable
              style="width: 250px;">
            </el-input>
          </div>
          
          <div class="search-actions">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            <el-button type="warning" icon="el-icon-download" @click="handleExport">导出Excel</el-button>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 评价列表 -->
    <el-card class="table-card">
      <div class="table-header">
        <h3>评价列表</h3>
        <span class="total-count">共 {{ total }} 条数据</span>
      </div>
      
      <el-table 
        :data="reviewList" 
        v-loading="loading"
        stripe
        style="width: 100%">
        <el-table-column prop="id" label="评价ID" min-width="80" align="center"></el-table-column>
        
        <el-table-column label="商品图片" min-width="120" align="center">
          <template slot-scope="scope">
            <img 
              v-if="scope.row.productImage" 
              :src="scope.row.productImage" 
              class="product-image"
              @click="handlePreviewImage(scope.row.productImage)">
            <span v-else style="color: #999;">暂无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="productName" label="商品名称" min-width="180">
          <template slot-scope="scope">
            <span style="color: #303133; font-weight: 500;">{{ scope.row.productName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="orderNo" label="订单编号" min-width="160">
          <template slot-scope="scope">
            <span style="font-weight: 600; color: #606266;">{{ scope.row.orderNo }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="评价时间" min-width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="userNickname" label="用户昵称" min-width="120" align="center">
          <template slot-scope="scope">
            <span style="color: #606266;">{{ scope.row.userNickname || '未知用户' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="rating" label="评分" min-width="140" align="center">
          <template slot-scope="scope">
            <div class="rating-display">
              <span class="stars">{{ getStars(scope.row.rating) }}</span>
              <el-tag 
                :type="getRatingType(scope.row.rating)" 
                size="small">
                {{ scope.row.rating }}星
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="content" label="评价内容" min-width="250">
          <template slot-scope="scope">
            <div class="review-content">
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" min-width="280" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-document" @click="handleViewOrder(scope.row)">查看订单</el-button>
            <el-button type="text" icon="el-icon-goods" @click="handleViewProduct(scope.row)">查看商品</el-button>
            <el-button type="text" icon="el-icon-edit" style="color: #e6a23c;" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" style="color: #f56c6c;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 编辑评价对话框 -->
    <el-dialog 
      title="编辑评价" 
      :visible.sync="editDialogVisible" 
      width="600px"
      :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="商品名称：">
          <span>{{ editForm.productName }}</span>
        </el-form-item>
        
        <el-form-item label="用户昵称：">
          <span>{{ editForm.userNickname }}</span>
        </el-form-item>
        
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="editForm.rating" :max="5"></el-rate>
        </el-form-item>
        
        <el-form-item label="评价内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="editForm.content" 
            :rows="5"
            placeholder="请输入评价内容"
            maxlength="500"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmEdit" :loading="submitLoading">保存</el-button>
      </div>
    </el-dialog>
    
    <!-- 订单详情对话框 -->
    <el-dialog 
      title="订单详情" 
      :visible.sync="orderDetailDialogVisible" 
      width="900px"
      :close-on-click-modal="false">
      <div v-if="currentOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <h4 class="section-title">订单信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">订单编号：</span>
                <span class="info-value">{{ currentOrder.orderNo }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">订单状态：</span>
                <el-tag :type="getStatusType(currentOrder.status)" size="small">{{ currentOrder.status }}</el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">下单时间：</span>
                <span class="info-value">{{ formatDate(currentOrder.createTime) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">订单金额：</span>
                <span class="info-value" style="color: #f56c6c; font-weight: 600;">¥{{ currentOrder.totalAmount }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 收货信息 -->
        <div class="detail-section">
          <h4 class="section-title">收货信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">收货人：</span>
                <span class="info-value">{{ currentOrder.receiverName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span class="info-value">{{ currentOrder.receiverPhone }}</span>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="info-item">
                <span class="info-label">收货地址：</span>
                <span class="info-value">{{ currentOrder.receiverAddress }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 商品信息 -->
        <div class="detail-section">
          <h4 class="section-title">商品信息</h4>
          <el-table :data="currentOrder.details" border stripe>
            <el-table-column label="商品图片" min-width="100" align="center">
              <template slot-scope="scope">
                <img 
                  v-if="scope.row.productImage" 
                  :src="scope.row.productImage" 
                  class="product-image"
                  @click="handlePreviewImage(scope.row.productImage)">
                <span v-else style="color: #999;">暂无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="200"></el-table-column>
            <el-table-column prop="price" label="单价" min-width="100" align="center">
              <template slot-scope="scope">
                <span style="color: #f56c6c;">¥{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" min-width="80" align="center"></el-table-column>
            <el-table-column label="小计" min-width="120" align="center">
              <template slot-scope="scope">
                <span style="color: #f56c6c; font-weight: 600;">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDetailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    
    <!-- 商品详情对话框 -->
    <el-dialog 
      title="商品详情" 
      :visible.sync="productDetailDialogVisible" 
      width="800px"
      :close-on-click-modal="false">
      <div v-if="currentProduct" class="product-detail">
        <el-row :gutter="20">
          <el-col :span="10">
            <div class="product-images">
              <img :src="currentProductImage" class="main-image">
              <div class="thumbnail-list" v-if="currentProduct.images && currentProduct.images.length > 1">
                <img 
                  v-for="(img, index) in currentProduct.images" 
                  :key="index"
                  :src="img"
                  :class="{ active: currentProductImage === img }"
                  @click="currentProductImage = img"
                  class="thumbnail-image">
              </div>
            </div>
          </el-col>
          <el-col :span="14">
            <div class="product-info-detail">
              <h3 class="product-name">{{ currentProduct.name }}</h3>
              <div class="product-price">
                <span class="price-label">价格：</span>
                <span class="price-value">¥{{ currentProduct.price }}</span>
              </div>
              <div class="product-stock">
                <span class="stock-label">库存：</span>
                <span class="stock-value">{{ currentProduct.stock }}</span>
              </div>
              <div class="product-status">
                <span class="status-label">状态：</span>
                <el-tag :type="currentProduct.status === '上架' ? 'success' : 'info'" size="small">
                  {{ currentProduct.status }}
                </el-tag>
              </div>
              <div class="product-category">
                <span class="category-label">分类：</span>
                <span class="category-value">{{ currentProduct.categoryName }}</span>
              </div>
              <div class="product-description">
                <h4>商品描述</h4>
                <p>{{ currentProduct.description }}</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="productDetailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    
    <!-- 图片预览对话框 -->
    <el-dialog 
      title="图片预览" 
      :visible.sync="imagePreviewVisible" 
      width="800px"
      :close-on-click-modal="true">
      <div class="image-preview-container">
        <img :src="previewImageUrl" class="preview-image">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminReviewList, adminUpdateReview, adminDeleteReview, exportReviews } from '@/api/review';
import { getAdminOrderDetail } from '@/api/adminOrder';
import { getProductDetail } from '@/api/product';

export default {
  name: 'AdminReviewManage',
  data() {
    return {
      // 搜索参数
      searchParams: {
        page: 1,
        size: 10,
        rating: null,
        content: ''
      },
      
      // 评价列表
      reviewList: [],
      total: 0,
      loading: false,
      
      // 编辑对话框
      editDialogVisible: false,
      editForm: {
        id: null,
        productName: '',
        userNickname: '',
        rating: 5,
        content: ''
      },
      editRules: {
        rating: [
          { required: true, message: '请选择评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      },
      submitLoading: false,
      
      // 订单详情对话框
      orderDetailDialogVisible: false,
      currentOrder: null,
      
      // 商品详情对话框
      productDetailDialogVisible: false,
      currentProduct: null,
      currentProductImage: '',
      
      // 图片预览
      imagePreviewVisible: false,
      previewImageUrl: ''
    };
  },
  
  created() {
    this.loadReviewList();
  },
  
  methods: {
    /**
     * 加载评价列表
     */
    async loadReviewList() {
      this.loading = true;
      try {
        const params = {
          page: this.searchParams.page,
          size: this.searchParams.size
        };
        
        if (this.searchParams.rating !== null) {
          params.rating = this.searchParams.rating;
        }
        
        if (this.searchParams.content) {
          params.content = this.searchParams.content;
        }
        
        const response = await getAdminReviewList(params);
        
        if (response.data.success) {
          const pageData = response.data.data;
          this.reviewList = pageData.records || [];
          this.total = pageData.total || 0;
        } else {
          this.$notify({
            title: '错误',
            message: response.data.message || '加载评价列表失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载评价列表失败',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 获取星星显示
     */
    getStars(rating) {
      return '⭐'.repeat(rating);
    },
    
    /**
     * 获取评分类型
     */
    getRatingType(rating) {
      if (rating === 5) return 'success';
      if (rating === 4) return '';
      if (rating === 3) return 'warning';
      return 'danger';
    },
    
    /**
     * 获取订单状态类型
     */
    getStatusType(status) {
      const typeMap = {
        '待发货': 'warning',
        '已发货': 'primary',
        '已收货': 'success'
      };
      return typeMap[status] || 'info';
    },
    
    /**
     * 搜索
     */
    handleSearch() {
      this.searchParams.page = 1;
      this.loadReviewList();
    },
    
    /**
     * 重置
     */
    handleReset() {
      this.searchParams = {
        page: 1,
        size: 10,
        rating: null,
        content: ''
      };
      this.loadReviewList();
    },
    
    /**
     * 查看订单详情
     */
    async handleViewOrder(row) {
      this.orderDetailDialogVisible = true;
      
      try {
        const response = await getAdminOrderDetail(row.orderId);
        if (response.data.success) {
          this.currentOrder = response.data.data;
        } else {
          this.$notify({
            title: '错误',
            message: response.data.message || '加载订单详情失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载订单详情失败',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    /**
     * 查看商品详情
     */
    async handleViewProduct(row) {
      this.productDetailDialogVisible = true;
      
      try {
        const response = await getProductDetail(row.productId);
        if (response.data.success) {
          this.currentProduct = response.data.data;
          // 处理图片
          if (this.currentProduct.images) {
            if (typeof this.currentProduct.images === 'string') {
              this.currentProduct.images = this.currentProduct.images.split(',');
            }
            this.currentProductImage = this.currentProduct.images[0];
          }
        } else {
          this.$notify({
            title: '错误',
            message: response.data.message || '加载商品详情失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载商品详情失败',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    /**
     * 编辑评价
     */
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        productName: row.productName,
        userNickname: row.userNickname,
        rating: row.rating,
        content: row.content
      };
      this.editDialogVisible = true;
    },
    
    /**
     * 确认编辑
     */
    handleConfirmEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return;
        
        this.submitLoading = true;
        try {
          const data = {
            reviewId: this.editForm.id,
            rating: this.editForm.rating,
            content: this.editForm.content
          };
          
          const response = await adminUpdateReview(data);
          
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '评价更新成功',
              type: 'success',
              duration: 2000
            });
            
            this.editDialogVisible = false;
            this.loadReviewList();
          } else {
            this.$notify({
              title: '错误',
              message: response.data.message || '评价更新失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '评价更新失败',
            type: 'error',
            duration: 2000
          });
        } finally {
          this.submitLoading = false;
        }
      });
    },
    
    /**
     * 删除评价
     */
    handleDelete(row) {
      this.$confirm('确定要删除该评价吗？删除后无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await adminDeleteReview({ reviewId: row.id });
          
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '评价删除成功',
              type: 'success',
              duration: 2000
            });
            
            this.loadReviewList();
          } else {
            this.$notify({
              title: '错误',
              message: response.data.message || '评价删除失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '评价删除失败',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    /**
     * 预览图片
     */
    handlePreviewImage(imageUrl) {
      this.previewImageUrl = imageUrl;
      this.imagePreviewVisible = true;
    },
    
    /**
     * 导出Excel
     */
    handleExport() {
      const params = {};
      
      if (this.searchParams.rating !== null) {
        params.rating = this.searchParams.rating;
      }
      
      if (this.searchParams.content) {
        params.content = this.searchParams.content;
      }
      
      const exportUrl = exportReviews(params);
      window.open(exportUrl, '_blank');
      
      this.$notify({
        title: '提示',
        message: '正在导出，请稍候...',
        type: 'info',
        duration: 2000
      });
    },
    
    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.searchParams.size = size;
      this.searchParams.page = 1;
      this.loadReviewList();
    },
    
    /**
     * 当前页改变
     */
    handleCurrentChange(page) {
      this.searchParams.page = page;
      this.loadReviewList();
    },
    
    /**
     * 格式化日期
     */
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hour = String(d.getHours()).padStart(2, '0');
      const minute = String(d.getMinutes()).padStart(2, '0');
      const second = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }
  }
};
</script>

<style scoped>
.admin-review-manage {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 40px);
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  height: 140px;
}

.search-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-item label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.search-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* 表格卡片 */
.table-card {
  border-radius: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.total-count {
  color: #666;
  font-size: 14px;
}

/* 商品图片 */
.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.1);
}

/* 评分显示 */
.rating-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.stars {
  font-size: 16px;
}

/* 评价内容 */
.review-content {
  color: #606266;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 订单详情 */
.order-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #2c5f2d;
  color: #2c5f2d;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  margin-bottom: 12px;
  line-height: 1.8;
}

.info-label {
  color: #666;
  font-weight: 500;
  margin-right: 8px;
}

.info-value {
  color: #303133;
}

/* 商品详情 */
.product-detail {
  padding: 20px 0;
}

.product-images {
  text-align: center;
}

.main-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
}

.thumbnail-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

.thumbnail-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.thumbnail-image:hover {
  transform: scale(1.1);
}

.thumbnail-image.active {
  border-color: #2c5f2d;
}

.product-info-detail {
  padding-left: 20px;
}

.product-name {
  font-size: 22px;
  color: #303133;
  margin: 0 0 20px 0;
  font-weight: 600;
}

.product-price,
.product-stock,
.product-status,
.product-category {
  margin-bottom: 15px;
  line-height: 1.8;
}

.price-label,
.stock-label,
.status-label,
.category-label {
  color: #666;
  font-weight: 500;
  margin-right: 8px;
}

.price-value {
  color: #f56c6c;
  font-size: 24px;
  font-weight: 600;
}

.stock-value,
.category-value {
  color: #303133;
}

.product-description {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.product-description h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.product-description p {
  color: #606266;
  line-height: 1.8;
  margin: 0;
}

/* 图片预览 */
.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框 */
.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-actions {
    margin-left: 0;
    width: 100%;
    flex-wrap: wrap;
  }
}
</style>

